<template>
  <div class="login-page">
    <div class="login-container">
      <h2>用户登录</h2>
      <div class="input-group">
        <input type="text" v-model="userId" placeholder="请输入手机号">
      </div>
      <div class="input-group">
        <input type="password" v-model="password" placeholder="请输入密码">
      </div>
      <button class="login-btn" @click="login">登录</button>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import axios from 'axios'

const router = useRouter()
const route = useRoute()
const userId = ref('')
const password = ref('')

const login = async () => {
  try {
    const res = await axios.post('/user/login', null, {
      params: {
        userId: userId.value,
        password: password.value
      }
    })

    if (res.data) {
      localStorage.setItem('userId', userId.value)
      // 如果有重定向地址，则跳转到重定向地址
      const redirect = route.query.redirect || '/'
      router.push(redirect)
    } else {
      alert('用户名或密码错误')
    }
  } catch (error) {
    console.error('登录失败:', error)
    alert('登录失败，请重试')
  }
}
</script>

<style scoped>
.login-page {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f7f8fa;
}

.login-container {
  width: 300px;
  padding: 30px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

h2 {
  text-align: center;
  margin-bottom: 24px;
  color: #333;
}

.input-group {
  margin-bottom: 16px;
}

input {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 14px;
}

input:focus {
  outline: none;
  border-color: #0097ff;
}

.login-btn {
  width: 100%;
  padding: 12px;
  background: #0097ff;
  color: #fff;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  cursor: pointer;
}

.login-btn:active {
  opacity: 0.9;
}
</style>